package com.techsoul.module.order.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.techsoul.common.core.constant.ApiConstants;
import com.techsoul.common.core.exception.ExcelException;
import com.techsoul.common.core.exception.ParamException;
import com.techsoul.common.core.pojo.vo.UserVo;
import com.techsoul.common.core.util.ServletUtils;
import com.techsoul.common.core.util.bean.BeanUtils;
import com.techsoul.common.core.util.collection.ListUtils;
import com.techsoul.common.core.util.id.IdWorker;
import com.techsoul.common.core.util.lang.DateUtils;
import com.techsoul.common.core.util.lang.NumberUtils;
import com.techsoul.common.core.util.lang.StringUtils;
import com.techsoul.common.core.util.poi.ExcelImport;
import com.techsoul.common.security.service.TokenService;
import com.techsoul.module.basic.mapper.StoreMapper;
import com.techsoul.module.basic.pojo.vo.CustomerVo;
import com.techsoul.module.basic.pojo.vo.StoreVo;
import com.techsoul.module.basic.service.ICustomerService;
import com.techsoul.module.basic.service.IStoreService;
import com.techsoul.module.goods.enmus.SpuStatusEnum;
import com.techsoul.module.goods.mapper.SpuMapper;
import com.techsoul.module.goods.pojo.entity.Spu;
import com.techsoul.module.order.enmus.SalesOrderSourceEnum;
import com.techsoul.module.order.enmus.SalesOrderStatusEnum;
import com.techsoul.module.order.enmus.SalesOrderTypeEnum;
import com.techsoul.module.order.mapper.SalesOrderHisMapper;
import com.techsoul.module.order.mapper.SalesOrderItemHisMapper;
import com.techsoul.module.order.pojo.entity.SalesOrderHis;
import com.techsoul.module.order.pojo.entity.SalesOrderItemHis;
import com.techsoul.module.order.pojo.param.SalesOrderItemHisSaveParam;
import com.techsoul.module.order.pojo.param.SalesOrderItemHisSearchParam;
import com.techsoul.module.order.pojo.vo.SalesOrderItemHisVo;
import com.techsoul.module.order.pojo.vo.SalesOrderItemVo;
import com.techsoul.module.order.service.ISalesOrderItemHisService;
import com.techsoul.module.pms.mapper.CustGoodsMapMapper;
import com.techsoul.module.goods.mapper.SkuMapper;
import com.techsoul.module.goods.pojo.entity.Sku;
import com.techsoul.module.pms.pojo.vo.CustGoodsMapVo;
import com.techsoul.module.system.enmus.ErrorType;
import com.techsoul.module.system.mapper.OperationLogMapper;
import com.techsoul.module.system.pojo.entity.OperationLog;
import com.techsoul.module.system.service.IGeneralSeqService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 销售订单明细 Service实现
 *
 * @author liuen
 * @date 2021-07-31
 */
@Slf4j
@Service
@Transactional(readOnly = true)
public class SalesOrderItemHisServiceImpl implements ISalesOrderItemHisService {

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private SalesOrderItemHisMapper mapper;

    @Autowired
    private TokenService tokenService;
    @Autowired
    private ICustomerService iCustomerService;
    @Autowired
    private SpuMapper spuMapper;

    @Autowired
    private SkuMapper skuMapper;
    @Autowired
    private IGeneralSeqService generalSeqService;
    @Autowired
    private StoreMapper storeMapper;
    @Autowired
    private SalesOrderHisMapper orderMapper;
    @Autowired
    private OperationLogMapper operationLogMapper;

    @Autowired
    private IStoreService iStoreService;

    @Autowired
    private CustGoodsMapMapper custGoodsMapMapper;
    /**
     * 新增
     * @param params
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public String insert(SalesOrderItemHisSaveParam params) {
        UserVo user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        SalesOrderItemHis entity = new SalesOrderItemHis();
        BeanUtils.copyProperties(params, entity);
        entity.setId(idWorker.nextId() + "").preInsert(user.getId());
        this.mapper.insert(entity);
        return entity.getId();
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public Integer delete(String id) {
        return this.mapper.deleteById(id);
    }

    /**
     * 批量删除
     * @param idList
     */
    @Transactional(readOnly = false)
    @Override
    public Integer batchDelete(List<String> idList) {
        if (ListUtils.isNotEmpty(idList)) {
            return this.mapper.deleteBatchIds(idList);
        } else {
            return 0;
        }
    }

    /**
     * 修改
     * @param params
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public Integer update(SalesOrderItemHisSaveParam params) {
        SalesOrderItemHis entityFromDb = this.mapper.selectById(params.getId());
        if (entityFromDb == null) {
            throw new ParamException("id=" + params.getId());
        }
        UserVo user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        BeanUtils.copyProperties(params, entityFromDb);
        entityFromDb.preUpdate(user.getId());
        return this.mapper.updateById(entityFromDb);
    }
    /**
     * 修改
     * @param id
     * @param params
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public Integer update(String id, SalesOrderItemHisSaveParam params) {
        UserVo user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        SalesOrderItemHis entityFromDb = this.mapper.selectById(id);
        if (entityFromDb == null) {
            throw new ParamException("id=" + id);
        }
        BeanUtils.copyProperties(params, entityFromDb);
        entityFromDb.preUpdate(user.getId());
        return this.mapper.updateById(entityFromDb);
    }

    /**
     * 详情
     * @param id
     * @return
     */
    @Override
    public SalesOrderItemHisVo findById(String id) {
        return this.mapper.findById(id);
    }

    /**
     * 列表
     * @param params
     * @return
     */
    @Override
    public List<SalesOrderItemHisVo> findAll(SalesOrderItemHisSearchParam params) {
        return this.mapper.findAll(params);
    }

    /**
     * 列表-分页
     * @param params
     * @param current
     * @param pageSize
     * @return
     */
    @Override
    public IPage<SalesOrderItemHisVo> findAll(SalesOrderItemHisSearchParam params, Integer current, Integer pageSize) {
        return this.mapper.findAll(new Page<>(current, pageSize), params);
    }

    @Override
    public SalesOrderItemVo removeSpecialChar(SalesOrderItemVo input){
        Pattern p =null;
        Matcher m = null;;
        String rt = "";
        if(StringUtils.isNull(input.getGroupOrSpu())||input.getGroupOrSpu()==""){
            input.setGroupOrSpu("单品");
        }else{
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getGroupOrSpu());
            rt = m.replaceAll("");
            input.setGroupOrSpu(rt);
        }
        if(!StringUtils.isNull(input.getCustSalesOrderNo())) {
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getCustSalesOrderNo());
            rt = m.replaceAll("");
            input.setCustSalesOrderNo(rt);
        }
        if(!StringUtils.isNull(input.getCustSalesOrderItemNo())) {
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getCustSalesOrderItemNo());
            rt = m.replaceAll("");
            input.setCustSalesOrderItemNo(rt);
        }

        if(!StringUtils.isNull(input.getStoreName())) {
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getStoreName());
            rt = m.replaceAll("");
            input.setStoreName(rt);
        }

        if(!StringUtils.isNull(input.getCustSkuId())) {
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getCustSkuId());
            rt = m.replaceAll("");
            input.setCustSkuId(rt);
        }

        if(!StringUtils.isNull(input.getCustSpuId())) {
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getCustSpuId());
            rt = m.replaceAll("");
            input.setCustSpuId(rt);
        }

        if(!StringUtils.isNull(input.getSpuName())) {
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getSpuName());
            rt = m.replaceAll("");
            input.setSpuName(rt);
        }
        if(!StringUtils.isNull(input.getStoreName())){
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getStoreName());
            rt = m.replaceAll("");
            input.setStoreName(rt);
        }
        if(!StringUtils.isNull(input.getSupplierName())){
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getSupplierName());
            rt = m.replaceAll("");
            input.setSupplierName(rt);
        }
        if(!StringUtils.isNull(input.getOrderTime())){
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getOrderTime());
            rt = m.replaceAll("");
            input.setSupplierName(rt);
        }
        if(!StringUtils.isNull(input.getCustRelSalesPrice())){
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getCustRelSalesPrice());
            rt = m.replaceAll("");
            if(StringUtils.isDouble(rt)){
                input.setCustRelSalesPrice(rt);
            }else{
                rt = rt.substring(1);
                input.setCustRelSalesPrice(rt);
            }


        }
        if(!StringUtils.isNull(input.getCustCashPaymentAmt())){
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getCustCashPaymentAmt());
            rt = m.replaceAll("");
            if(StringUtils.isDouble(rt)){
                input.setCustCashPaymentAmt(rt);
            }else{
                rt = rt.substring(1);
                input.setCustCashPaymentAmt(rt);
            }


        }
        if(!StringUtils.isNull(input.getCustMilePaymentAmt())){
            p = Pattern.compile("\\s*|\t|\r|\n");
            m = p.matcher(input.getCustMilePaymentAmt());
            rt = m.replaceAll("");
            if(StringUtils.isDouble(rt)){
                input.setCustMilePaymentAmt(rt);
            }else{
                rt = rt.substring(1);
                input.setCustMilePaymentAmt(rt);
            }

        }
        return input;
    }
    /**
     * 生成商品SKU
     */
    @Override
    public Sku generateNewSku(SalesOrderItemVo materialBuyPriceVo, Spu spu){
        Sku sku = new Sku();
        UserVo user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();


        sku.setSpuId(spu.getId());
        sku.setCustSkuId(materialBuyPriceVo.getCustSkuId());
        // sku.setCategoryName(materialBuyPriceVo.getCategoryName());
        // sku.setImage(materialBuyPriceVo.getImage());
        // sku.setSpec(materialBuyPriceVo.getMaterialGuige());
        sku.setSkuName(materialBuyPriceVo.getSkuName());
        sku.setStatus(SpuStatusEnum.CREATED.getStatusName());
        sku.setIsValid("1");
        sku.setId(idWorker.nextId() + "").preInsert(user.getId());
        skuMapper.insert(sku);
        return sku;
    }
    /**
     * 生成商品
     */
    @Override
    public Spu generateNewSpu(SalesOrderItemVo materialBuyPriceVo){
        Spu spu = new Spu();
        UserVo user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        spu.setTitle(materialBuyPriceVo.getSkuName());
        spu.setCategoryName(materialBuyPriceVo.getCategoryName());
        spu.setImage(materialBuyPriceVo.getImage());
        spu.setIntroduction(materialBuyPriceVo.getSkuName());
        spu.setSpuName(materialBuyPriceVo.getSkuName());
        spu.setStatus(SpuStatusEnum.CREATED.getStatus());

        spu.setId(idWorker.nextId() + "").preInsert(user.getId());
        spuMapper.insert(spu);
        return spu;
    }

    @Transactional(readOnly = false)
    @Override
    public SalesOrderHis addMigrationSalesOrder(SalesOrderItemVo salesOrderItemVo,UserVo user,CustomerVo customerVo,int line) {

        SalesOrderHis salesOrder = new SalesOrderHis();
        String importError = "";
        String errorFlag="N";
        if(!StringUtils.isNull(salesOrderItemVo.getStoreId())){
            String storeCode =this.replaceStoreCode(salesOrderItemVo.getStoreId());
            //   StoreVo storeVo = storeMapper.findByCode(storeCode);

            salesOrder.setStoreId(storeCode);
            //  if(storeVo!=null){
            //      salesOrder.setStoreId(storeVo.getStoreCode());
            //  }else{

            //   }
        }else{

        }
        String orderNo = this.generalSeqService.generateSeq("oms_sales_order");
        salesOrder.setCustSalesOrderNo(salesOrderItemVo.getCustSalesOrderNo());
        salesOrder.setSalesOrderNo(orderNo);
        salesOrder.setCustomerId(customerVo.getId());
        salesOrder.setCustomerName(customerVo.getCustomerName());
        salesOrder.setDeliveryStatus(salesOrderItemVo.getDeliveryStatus());
        if(salesOrderItemVo.getFreightFee()!=null){
            salesOrder.setFreightFee(BigDecimal.valueOf(salesOrderItemVo.getFreightFee()));
        }

        salesOrder.setOrderStatus(salesOrderItemVo.getCustOrderStatus());
        salesOrder.setOrderType(SalesOrderTypeEnum.BySku.getValue());
        salesOrder.setPayStatus(salesOrderItemVo.getPaymentStatus());
        salesOrder.setSourceType(SalesOrderSourceEnum.Byexcel.getValue());
        salesOrder.setStoreSource(salesOrderItemVo.getStoreSource());
        salesOrder.setErrorFlag(errorFlag);
        salesOrder.setId(idWorker.nextId() + "").preInsert(user != null ? user.getId() : ApiConstants.DEFAULT_USER_ID);
        this.orderMapper.insert(salesOrder);


        return salesOrder;


    }
    @Transactional(readOnly = false)
    @Override
    public SalesOrderItemHis addMigrationItem(SalesOrderHis newSalesOrder, SalesOrderItemVo data,UserVo user,int itemNo,int line){

        SalesOrderItemHis salesOrderItem = new SalesOrderItemHis();
        salesOrderItem.setErrorFlag(newSalesOrder.getErrorFlag());
        if(!StringUtils.isNull(newSalesOrder.getErrorCode())){
            salesOrderItem.setErrorCode(newSalesOrder.getErrorCode());
            if(newSalesOrder.getErrorCode().equals("101")){
                salesOrderItem.setErrorFlag("Y");
            }
        }
        String errorMsg = newSalesOrder.getImportErrorMesg();
        String itemErrorMsg = "明细保存：";

        BeanUtils.copyProperties(data, salesOrderItem);

        StoreVo storeVo=null;
        if(StringUtils.isNull(data.getStoreId())){

            salesOrderItem.setGenAccFailedReason("店铺数据没有维护 ");
            salesOrderItem.setCustSalesOrderNo(data.getCustSalesOrderNo());
            salesOrderItem.setStatus(SalesOrderStatusEnum.NEWREC.getValue());
            if(!StringUtils.isNull(salesOrderItem.getErrorCode())){
                salesOrderItem.setErrorCode(salesOrderItem.getErrorCode().concat(";").concat("601"));
            }else{
                salesOrderItem.setErrorCode("601");
            }
            this.genOperationLog(salesOrderItem,user);
            itemErrorMsg=itemErrorMsg.concat("店铺数据没有维护 ");
        }else{
            String storeCode =this.replaceStoreCode(data.getStoreId());
            storeVo = storeMapper.findByCode(storeCode);
            salesOrderItem.setStoreId(storeCode);
        }

        salesOrderItem.setSalesOrderNo(newSalesOrder.getSalesOrderNo());
        salesOrderItem.setSalesOrderId(newSalesOrder.getId());
        salesOrderItem.setSalesOrderItemNo(String.valueOf(itemNo));
        salesOrderItem.setCustomerNo(newSalesOrder.getCustomerId());
        salesOrderItem.setCustomerName(newSalesOrder.getCustomerName());
        salesOrderItem.setCustSkuId(data.getCustSkuId());
        salesOrderItem.setCustSpuId(data.getCustSpuId());
        CustGoodsMapVo custGoodsMapVo= custGoodsMapMapper.findByCustGoodNoAndSkuNo(data.getCustSpuId(),data.getCustSkuId(),newSalesOrder.getCustomerId());
        if(custGoodsMapVo==null){
            custGoodsMapVo= custGoodsMapMapper.findByCustGoodNoAndSkuNo(data.getCustSpuId(),"通用",newSalesOrder.getCustomerId());
        }
        if(custGoodsMapVo==null){//映射表内没有

            salesOrderItem.setGenAccFailedReason("商品价格不存在本系统，请先导入商品价格 ");
            salesOrderItem.setCustSalesOrderNo(data.getCustSalesOrderNo());
            salesOrderItem.setStatus(SalesOrderStatusEnum.NEWREC.getValue());
            if(!StringUtils.isNull(salesOrderItem.getErrorCode())){
                salesOrderItem.setErrorCode(salesOrderItem.getErrorCode().concat(";").concat("201"));
            }else{
                salesOrderItem.setErrorCode("201");
            }
            this.genOperationLog(salesOrderItem,user);

            itemErrorMsg=itemErrorMsg.concat("商品价格不存在本系统，请先导入商品价格 ");
        }else{
            salesOrderItem.setSpuId(custGoodsMapVo.getSpuId());
            salesOrderItem.setSkuId(custGoodsMapVo.getSkuId());
            salesOrderItem.setMaterialMapId(custGoodsMapVo.getId());

        }

        if(data.getQty()==null){
            if(!StringUtils.isNull(salesOrderItem.getErrorCode())){
                salesOrderItem.setErrorCode(salesOrderItem.getErrorCode().concat(";").concat("103"));
            }else{
                salesOrderItem.setErrorCode("103");
            }
            salesOrderItem.setErrorFlag("Y");
            itemErrorMsg=itemErrorMsg.concat("销售件数为空 ");
            salesOrderItem.setCustSalesOrderNo(data.getCustSalesOrderNo());
            this.genOperationLog(salesOrderItem,user);
        }else if(String.valueOf(data.getQty()).contains(".")){
            if(!StringUtils.isNull(salesOrderItem.getErrorCode())){
                salesOrderItem.setErrorCode(salesOrderItem.getErrorCode().concat(";").concat("103"));
            }else{
                salesOrderItem.setErrorCode("103");
            }
            salesOrderItem.setErrorFlag("Y");
            itemErrorMsg=itemErrorMsg.concat("销售件数不是大于0的整数 ");
            salesOrderItem.setCustSalesOrderNo(data.getCustSalesOrderNo());
            this.genOperationLog(salesOrderItem,user);
        }else if(data.getQty()<0) {
            if(!StringUtils.isNull(salesOrderItem.getErrorCode())){
                salesOrderItem.setErrorCode(salesOrderItem.getErrorCode().concat(";").concat("103"));
            }else{
                salesOrderItem.setErrorCode("103");
            }
            salesOrderItem.setErrorFlag("Y");

            itemErrorMsg=itemErrorMsg.concat("销售件数不是大于0的整数 ");
            salesOrderItem.setCustSalesOrderNo(data.getCustSalesOrderNo());
            this.genOperationLog(salesOrderItem,user);
        }
        if(StringUtils.isNull(data.getCustSpuId())){
            //||StringUtils.isNull(data.getCustSkuId())
            if(!StringUtils.isNull(salesOrderItem.getErrorCode())){
                salesOrderItem.setErrorCode(salesOrderItem.getErrorCode().concat(";").concat("100"));
            }else{
                salesOrderItem.setErrorCode("100");
            }
            salesOrderItem.setErrorFlag("Y");
            itemErrorMsg = itemErrorMsg.concat("对方商品ID为空");
            salesOrderItem.setCustSalesOrderNo(data.getCustSalesOrderNo());
            this.genOperationLog(salesOrderItem,user);
        }
        salesOrderItem.setId(idWorker.nextId() + "").preInsert(user != null ? user.getId() : ApiConstants.DEFAULT_USER_ID);
        if(StringUtils.isNull(salesOrderItem.getStatus())){
            salesOrderItem.setStatus(SalesOrderStatusEnum.NEWREC.getValue());
        }

        salesOrderItem.setOriginalQty(data.getQty());
        if(storeVo!=null){
            salesOrderItem.setSupplierNo(storeVo.getSupplierId());
            salesOrderItem.setSupplierName(storeVo.getSupplierName());
            salesOrderItem.setStoreName(storeVo.getStoreName());
        }else{
            salesOrderItem.setSupplierNo("");
            salesOrderItem.setSupplierName("");
            salesOrderItem.setStoreName("");
        }


        if(StringUtils.isNull(salesOrderItem.getErrorFlag())){
            salesOrderItem.setErrorFlag("N");
        }
        if(!StringUtils.isNull(data.getOrderTime())){
            try{
                String datestr= data.getOrderTime();
                Date jobdt=new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.UK).parse(datestr);

                salesOrderItem.setCreateTime(jobdt);
                salesOrderItem.setOrderTime(DateUtils.formatDateTime(jobdt));
            }catch(Exception e){
                if(!StringUtils.isNull(salesOrderItem.getErrorCode())){
                    salesOrderItem.setErrorCode(salesOrderItem.getErrorCode().concat(";").concat("105"));
                }else{
                    salesOrderItem.setErrorCode("105");
                }
                salesOrderItem.setErrorFlag("Y");
                itemErrorMsg=itemErrorMsg.concat("日期格式不正确 ");

            }

        }
        salesOrderItem.setImportErrorMesg(itemErrorMsg);
        if(!StringUtils.isNull(data.getCustRelSalesPrice())){
            Double price = NumberUtils.mul(data.getQty().doubleValue(),Double.valueOf(data.getCustRelSalesPrice()));
            salesOrderItem.setCustRelSalesPrice(String.valueOf(price));
            salesOrderItem.setCustRelSalesUnitPrice(BigDecimal.valueOf(Double.valueOf(data.getCustRelSalesPrice())));
        }
        if(data.getCouponDiscount()!=null){
            salesOrderItem.setCouponDiscount(BigDecimal.valueOf(data.getCouponDiscount()));
        }
        if(data.getMileageCouponDiscount()!=null) {

            salesOrderItem.setMileageCouponDiscount(BigDecimal.valueOf(data.getMileageCouponDiscount()));
        }
        try{
            this.mapper.insert(salesOrderItem);
        }catch(Exception e){
            log.error("数据导入失败：", e);
            salesOrderItem.setImportErrorMesg(e.getMessage().substring(0,200));
            salesOrderItem.setCustSalesOrderNo(String.valueOf(line));
            this.genOperationLog(salesOrderItem,user);
        }

        return salesOrderItem;
    }
    @Transactional(readOnly = false)
    @Override
    public void genOperationLog(SalesOrderItemHis data,UserVo user ) {
        OperationLog operationLog = new OperationLog();
        operationLog.setOperationType(ErrorType.ORDERIMPORT.getStatusName());
        String errormsg = " ";
        if(!StringUtils.isNull(data.getGenAccFailedReason())){
            errormsg = errormsg.concat(data.getGenAccFailedReason());
        }
        if(!StringUtils.isNull(data.getImportErrorMesg())){
            errormsg = errormsg.concat(data.getImportErrorMesg());
        }
        operationLog.setErrorMsg(errormsg);
        operationLog.setMethod(data.getErrorCode());
        operationLog.setLocation(data.getCustSalesOrderNo());
        operationLog.setId(idWorker.nextId() + "").preInsert(user != null ? user.getId() : ApiConstants.DEFAULT_USER_ID);
        if (user != null) {
            operationLog.setOperatorName(user.getUserName() + "(" + user.getNickName() + ")");
        }
        operationLogMapper.insert(operationLog);

    }


    private String replaceStoreCode(String storeCode){
        String rtStore = "贸易";
        if(storeCode.contains("南航贸易")){
            String num = storeCode.substring(4);
            String lastnum = "";
            if(num.length()==1){
                lastnum = "00".concat(num);
            }else if(num.length()==2){
                lastnum = "0".concat(num);
            }else{
                lastnum=num;
            }
            rtStore = rtStore.concat(lastnum);
        }else{
            rtStore = storeCode;
        }
        return rtStore;
    }
    /**
     * 历史数据导入
     * @param file
     * @return
     */
    @Transactional(readOnly = false)
    @Override
    public String dataMigration(String customerNo, MultipartFile file){
        List<SalesOrderItemVo> dataList = null;
        UserVo user = tokenService.getLoginUser(ServletUtils.getRequest()).getUser();
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        CustomerVo customerVo = iCustomerService.findById(customerNo);

        int successNum = 0;
        int failureNum = 0;
        int logNum = 0;
        try {
            ExcelImport excelImport = new ExcelImport(file, 1, 0);
            dataList = excelImport.getDataList(SalesOrderItemVo.class);
        } catch (Exception e) {
            log.error("获取数据信息失败!");
            throw new ExcelException("获取数据信息失败!");
        }
        if (ListUtils.isEmpty(dataList)) {
            throw new ExcelException("导入数据不能为空！");
        }

        if(dataList==null||dataList.size()==0){
            return "没有读取到数据";
        }
        SalesOrderItemVo firstdata = (SalesOrderItemVo)dataList.get(0);
        String custOrderNo ="";
        SalesOrderHis newSalesOrder = null;
        int itemNo = 0;
        int line = 0;
        List<String> custOrderNos = new ArrayList<String>();
        for (SalesOrderItemVo data : dataList) {
            data = this.removeSpecialChar(data);
            line++;
            // if(!data.getCustSalesOrderNo().equals(custOrderNo)){
            custOrderNo =data.getCustSalesOrderNo();
            if(!custOrderNos.contains(custOrderNo)){
                itemNo = 0;
                newSalesOrder = this.addMigrationSalesOrder(data,user,customerVo,line);
                if(newSalesOrder!=null){
                    //custOrderNo = data.getCustSalesOrderNo();
                    custOrderNos.add(custOrderNo);
                }else{
                    failureNum++;
                    logNum++;
                    continue;
                }
            }

            itemNo = itemNo++;
            if(newSalesOrder!=null){
                SalesOrderItemHis salesOrderItem = this.addMigrationItem(newSalesOrder,data,user,itemNo,line);
                if(salesOrderItem!=null){
                    successNum++;
                }else{
                    failureNum++;
                    logNum++;
                    continue;
                }
            }



        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误清查日志");
            OperationLog operationLog =new OperationLog();
            operationLog.setOperationType(ErrorType.ORDERIMPORT.getStatusName());
            operationLog.setErrorMsg(failureMsg.toString());
            operationLog.setMethod("导入模板-原始订单-批量导入");
            operationLog.setLocation("第"+line+"行");
            operationLog.setId(idWorker.nextId() + "").preInsert(user.getId());
            if (user != null) {
                operationLog.setOperatorName(user.getUserName() + "(" + user.getNickName() + ")");
            }
            operationLogMapper.insert(operationLog);
            // throw new ExcelException(failureMsg.toString());
            return "操作有"+failureNum+"行输入异常，请看日志";
        } else {
            if(logNum>0){
                successMsg.insert(0, "恭喜您，操作成功！共 " + successNum + " 条，另有：" +logNum+ " 条数据不能正常导入，已写入日志");

            }else{
                successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");

            }
        }
        return successMsg.toString();
    }
}
